package com.youxue.controller;

import com.alibaba.fastjson.JSONObject;
import com.cangshi.permission.entity.UserSubject;
import com.youxue.entity.*;
import com.youxue.permission.saver.SubjectHolder;
import com.youxue.service.CommentService;
import com.youxue.service.UserClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by 15c on 2018/1/20.
 */
@Controller
@RequestMapping("/comments")
public class CommentController {
    @Autowired
    CommentService commentService;
    @Autowired
    UserClassService userClassService;

    /**
     * 对一门课程添加评论
     * {"msg":"该用户没有权限访问当前url","error":201}
     *
     * @param comment
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/comment/add", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String addAComment(@RequestBody(required = false) Comment comment) {
        ErrorJsonObject errorJsonObject = null;
        CorrectJsonObject correctJsonObject = null;
        if (null == comment) {
            errorJsonObject = new ErrorJsonObject(101, "评论comment对象为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
         if (null == comment.getCommentContent() || null == comment.getCommentClassId() || "".equals(comment.getCommentContent())) {
            errorJsonObject = new ErrorJsonObject(102, "评论内容为空或评论课程id为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
            // 获取当前访问对象
            UserSubject subject = (UserSubject) SubjectHolder.getSubject();

            //获取当前的登录信息
            UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
            //获取当前的用户登录id
            int userId = userEntity.getUserId();

            UserClassKey userClassKey=new UserClassKey();
            userClassKey.setUserId(userId);
            userClassKey.setClassId(comment.getCommentClassId());
            UserClass userClass=new UserClass();
            userClass=userClassService.showAUserClassInfo(userClassKey);
            if (null==userClass){
                errorJsonObject = new ErrorJsonObject(110, "你还未学习过");
                return JSONObject.toJSONString(errorJsonObject);
            }

            //将登陆用户id封装进comment对象
            comment.setCommentUserId(userId);
            int result = commentService.addComment(comment);
            if (1 == result) {
                correctJsonObject = new CorrectJsonObject("添加评论成功");
                return JSONObject.toJSONString(correctJsonObject);

            } else {
                errorJsonObject = new ErrorJsonObject(103, "添加评论失败，请重试");
                return JSONObject.toJSONString(errorJsonObject);
            }


    }

    /**
     * 查询一门课程对应的所有评论,分页显示
     *
     * @param commentClassId
     * @param page           请求第几页
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/show", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showAComment(@RequestParam(required = false) Integer commentClassId,
                        @RequestParam(required = false) Integer page) {
        ErrorJsonObject errorJsonObject = null;
        CorrectJsonObject correctJsonObject = null;
        if (null == commentClassId || null == page) {
            errorJsonObject = new ErrorJsonObject(104, "评论课程id或page参数为空");
            return JSONObject.toJSONString(errorJsonObject);
        }

        //一页的信息条数
        int pageSize = 15;
        //获得总页数
        int allTaskNum = commentService.showAClassAllCommentCount(commentClassId);
        int resultAllPage = allTaskNum / pageSize;
        int resultRemainder = allTaskNum % pageSize;
        if (0 < resultRemainder) {
            resultAllPage = resultAllPage + 1;
        }
        if (0 >= page) {
            errorJsonObject = new ErrorJsonObject(105, "page参数不可为负");
            return JSONObject.toJSONString(errorJsonObject);
        }
        if (resultAllPage < page) {
            errorJsonObject = new ErrorJsonObject(106, "请求页数超额");
            return JSONObject.toJSONString(errorJsonObject);
        }
        //从那一条开始请求
        int startPos = pageSize * page - pageSize;
        System.out.println("-----------------" + startPos);
        List<Comment> commentList = new ArrayList<Comment>();
        commentList = commentService.showAClassAllCommentByPage(startPos, pageSize, commentClassId);
        correctJsonObject = new CorrectJsonObject("查询成功");
        correctJsonObject.setData(commentList);
        correctJsonObject.put("allPage", resultAllPage);
        return JSONObject.toJSONString(correctJsonObject);

    }

    /**
     * 查询一条评论详情
     *
     * @param commentId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/acommentinfo", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showACommentInfo(@RequestParam(required = false) Integer commentId) {
        ErrorJsonObject errorJsonObject = null;
        CorrectJsonObject correctJsonObject = null;
        if (null == commentId) {
            errorJsonObject = new ErrorJsonObject(106, "评论id为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        Comment comment = new Comment();
        comment = commentService.showACommentInfo(commentId);
        correctJsonObject = new CorrectJsonObject("查询成功");
        correctJsonObject.setData(comment);
        return JSONObject.toJSONString(correctJsonObject);
    }

    /**
     * 删除用户自己发布的评论
     *
     * @param commentId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/comment/delete", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String deleteAComment(@RequestParam(required = false) Integer commentId) {
        ErrorJsonObject errorJsonObject = null;
        CorrectJsonObject correctJsonObject = null;
        if (null == commentId) {
            errorJsonObject = new ErrorJsonObject(108, "评论id为空");
            return JSONObject.toJSONString(errorJsonObject);
        }
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();

        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();

        int resultUserId = commentService.showUserIdACommentForDelete(commentId);

        if (userId == resultUserId) {
            int result = commentService.deleteAComment(commentId);
            if (1 == result) {
                correctJsonObject = new CorrectJsonObject("删除成功");
                return JSONObject.toJSONString(correctJsonObject);
            } else {
                errorJsonObject = new ErrorJsonObject(110, "删除失败，请重试");
                return JSONObject.toJSONString(errorJsonObject);
            }

        } else {
            errorJsonObject = new ErrorJsonObject(109, "登录用户与评论创建用户id不匹配，无权删除该条评论");
            return JSONObject.toJSONString(errorJsonObject);
        }

    }



    /**
     * 课程评价图片上传入口
     *
     * @param request 用户请求
     * @param image   图片
     * @return 结果json
     */
    @ResponseBody
    @RequestMapping(value = "/image-upload", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String imageUpload(HttpServletRequest request, @RequestBody(required = false) String image) {
        System.out.println("image为：" + image + " end");
        ErrorJsonObject errorJsonObject;
        //指定头类型
        String headerPng = "data:image/png;base64,";
        String headerJpG = "data:image/jpeg;base64,";

        //获取服务器的路径
        String realPath = request.getSession().getServletContext().getRealPath("/resources/commentImg");

        System.out.println("realPath为：" + realPath + "  end");
        //声明图片地址
        String imgAddress = null;
        //获取扩展名
        String extensionName = ".png";
        System.out.println("--------------->" + extensionName);
        if (image != null && (image.indexOf(headerPng) != 0 || image.indexOf(headerJpG) != 0)) {
            String headPng = image.substring(0, headerPng.length());
            String headJpG = image.substring(0, headerJpG.length());
            if (headerJpG.equals(headJpG)) {
                //去掉头部
                image = image.substring(headerJpG.length());
                BASE64Decoder decoder = new BASE64Decoder();
                try {
                    if (!image.isEmpty()) {

                        //以当前时间加随机数命名上传文件
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                        String date = sdf.format(new java.util.Date());


                        //设置图片名为当前时间加随机数
                        imgAddress = date + new Random().nextInt() + extensionName;

                        //将文件上传到服务器
                        byte[] decodedBytes = decoder.decodeBuffer(image);

                        FileOutputStream out = new FileOutputStream(realPath + "/" + imgAddress);

                        out.write(decodedBytes);

                        out.close();

                        CorrectJsonObject correctJsonObject = new CorrectJsonObject("上传成功！");
                        correctJsonObject.setData(imgAddress);
                        return correctJsonObject.toString();

                    } else {

                        errorJsonObject = new ErrorJsonObject(108, "上传的文件不存在！");
                        return errorJsonObject.toJSONString();

                    }
                } catch (IOException e) {

                    errorJsonObject = new ErrorJsonObject(108, e.getMessage());
                    return errorJsonObject.toJSONString();

                }
            } else if (headerPng.equals(headPng)) {
                //去掉头部
                image = image.substring(headerPng.length());
                BASE64Decoder decoder = new BASE64Decoder();
                try {
                    if (!image.isEmpty()) {

                        //以当前时间加随机数命名上传文件
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                        String date = sdf.format(new java.util.Date());


                        //设置图片名为当前时间加随机数
                        imgAddress = date + new Random().nextInt() + extensionName;

                        //将文件上传到服务器
                        byte[] decodedBytes = decoder.decodeBuffer(image);

                        FileOutputStream out = new FileOutputStream(realPath + "/" + imgAddress);

                        out.write(decodedBytes);

                        out.close();

                        CorrectJsonObject correctJsonObject = new CorrectJsonObject("上传成功！");
                        correctJsonObject.setData(imgAddress);
                        return correctJsonObject.toString();

                    } else {

                        errorJsonObject = new ErrorJsonObject(108, "上传的文件不存在！");
                        return errorJsonObject.toJSONString();

                    }
                } catch (IOException e) {

                    errorJsonObject = new ErrorJsonObject(108, e.getMessage());
                    return errorJsonObject.toJSONString();

                }
            } else {
                errorJsonObject = new ErrorJsonObject(107, "文件不存在或格式不正确");
                return errorJsonObject.toJSONString();
            }
        } else {
            errorJsonObject = new ErrorJsonObject(107, "文件不存在或格式不正确");
            return errorJsonObject.toJSONString();
        }
    }


}
